package com.workingpub.commons.proxy;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.springframework.util.Assert;

import com.workingpub.commons.domain.Identifiable;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class DomainEntityProxy implements MethodInterceptor {
	private static final String Method_GetId = "getId";

	private Serializable entityId;
	private Class<? extends Identifiable<?>> target;

	public DomainEntityProxy(Class<? extends Identifiable<?>> clazz) {
		this.target = clazz;
	}

	public Object create(Serializable id) {
		entityId = id;
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(target);
		enhancer.setCallback(this);
		return enhancer.create();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		Assert.isTrue(Method_GetId.equals(method.getName()),
				"Domain entity instance is a proxy object, can't get the real value.");
		return entityId;
	}

}
